package com.situ.mall.common.util;

import org.apache.activemq.ScheduledMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jms.JmsProperties;
import org.springframework.jms.core.JmsMessagingTemplate;

import javax.jms.*;
import java.io.Serializable;

public class Activemq {

    @Autowired
    private static JmsMessagingTemplate jmsMessagingTemplate;
    public static <T extends Serializable> void delaySend(Destination queue, T data, Long time) {
        Connection conn = null;
        Session session = null;
        MessageProducer producer = null;

        ConnectionFactory connectionFactory = jmsMessagingTemplate.getConnectionFactory();
        System.out.println(connectionFactory);
        try {
            conn = connectionFactory.createConnection();
            conn.start();
            session = conn.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
            //创建一个生产者
            producer = session.createProducer(queue);
            producer.setDeliveryMode(JmsProperties.DeliveryMode.PERSISTENT.getValue());
            ObjectMessage message = session.createObjectMessage(data);
            message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time);
            producer.send(message);
            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (producer != null) {
                    producer.close();
                }
                if (session != null) {
                    session.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception ignored) {

            }
        }
    }
}
